/**
 * 
 */
package zhihu;

import java.util.LinkedHashMap;
import java.util.Map;

import org.apache.log4j.Logger;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import com.wixc.util.LoginUtil;
import com.wixc.util.RuoKuai;


/**
 * @author weichuanxi
 * @date 2016年3月18日
 */
public class ZhiHuLoginUtil {
	private static Logger log = Logger.getLogger(ZhiHuLoginUtil.class);
	public boolean Login(LoginUtil util, String name, String password) {
		if (!LoginUtil.checkUser(name, password)) {
			return false;
		}
		Map<String, String> header = new LinkedHashMap<String, String>();
		String html = util.Get("https://www.zhihu.com/#signin");
		Document doc = Jsoup.parse(html);
		String _xsrf = doc.select("input[name=_xsrf]").get(0).attr("value");
//		header.put("referer", "https://www.zhihu.com/");
//		header.put("accept", "*/*");
//		header.put("accept-encoding", "gzip, deflate");
//		header.put("accept-language", "zh-CN,zh;q=0.8");
//		header.put("x-requested-with", "XMLHttpRequest");
//		header.put("content-type", "application/x-www-form-urlencoded; charset=UTF-8");
//		header.put(":host", "www.zhihu.com");
//		header.put(":method", "POST");
//		header.put(":path:", "/login/email");
//		header.put(":scheme", "https");
//		header.put(":version", "HTTP/1.1");

		Map<String, String> postdata = new LinkedHashMap<String, String>();
		postdata.put("email", name);
		postdata.put("password", password);
		postdata.put("_xsrf", _xsrf);
		postdata.put("remember_me", "true");
		String status = TryIt(util, "https://www.zhihu.com/captcha.gif?r="+System.currentTimeMillis()+"&type=login",header, postdata);
		log.info("status："+status);
		if (null != status && "登陆成功".equals(status)) {
			return true;
		} else {
			return false;
		}
	}

	private String TryIt(LoginUtil util, String imgsrc,Map<String, String> header, Map<String, String> postdata) {
		if (imgsrc != null) {
			byte[] img = util.GetImg(imgsrc);
			String im = RuoKuai.createByByte("3040", img);
			Map<String, Object> imgmap = LoginUtil.json2Map(im);
			if (imgmap != null) {
				if (imgmap.get("Result") != null) {
					postdata.put("captcha", imgmap.get("Result").toString());
				}
			}
		}
		
		String html = util.Post("https://www.zhihu.com/login/email", header, postdata);
		Map<String, Object> map = LoginUtil.json2Map(html);
		String status = map.get("r") + "";
		String msg = map.get("msg") + "";
		log.info("msg："+msg);
		if ("0.0".equals(status)) {
			return "登陆成功";
		} else {
			return "登陆失败";
		}
	}

	public static void main(String[] args) throws Exception {

		String name = "18600909436@163.com";
		String password = "wcx3412232355";

		ZhiHuLoginUtil Loginutil = new ZhiHuLoginUtil();
		LoginUtil util = new LoginUtil();
		Loginutil.Login(util, name, password);
	}
}
